//
//  HMEmoticonTools.swift
//  MicroBlog
//
//  Created by Apple on 16/10/6.
//  Copyright © 2016年 Apple. All rights reserved.
//

import UIKit
//每页显示20个表情
let numberOfPage = 20
//最近表情沙盒路径
let RecentDataPath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("recentEmoticonArray.archiver")
//读取表情工具类
class HMEmoticonTools: NSObject {

    static let shareTools: HMEmoticonTools = HMEmoticonTools()
    
    //构造函数私有化,外界不能直接通过()创建类
    private override init() {
        super.init()
        
    }
    //获取Bundle对象
    lazy var emoticonsBundle: Bundle = {
        //获取bundle的路径
       let path = Bundle.main.path(forResource: "Emoticons.bundle", ofType: nil)!
        //通过路径创建对象
        let bundle = Bundle(path: path)!
        return bundle
    }()
    
    //给表情视图提供数据结构
    lazy var allEmoticonsArray: [[[HMEmoticon]]] = {
        return [
            [self.recentEmoticonArray],
            self.setctionEmoticon(emoticonArray:self.defaultEmoticonsArray),
            self.setctionEmoticon(emoticonArray:self.emojiEmoticonsArray),
            self.setctionEmoticon(emoticonArray:self.lxhEmoticonsArray),
        ]
    }()
    
    //最近表情
    private lazy var recentEmoticonArray: [HMEmoticon] = {
        if let localRecentData = self.loadRecentEmoticonArray() {
            //本地有最近表情
            return localRecentData
        } else {
            //本地没有最近表情
        }
        let emoticonArray = [HMEmoticon]()
        return emoticonArray
    }()
    
    //获取默认表情数据
    private lazy var defaultEmoticonsArray: [HMEmoticon] = {
        return self.loadEmoticonsArray(folderName: "default", fileName: "info.plist")
    }()
    
    //获取emoji表情数据
    private lazy var emojiEmoticonsArray: [HMEmoticon] = {
        return self.loadEmoticonsArray(folderName: "emoji", fileName: "info.plist")
    }()
    
    //获取lxh表情数据
    private lazy var lxhEmoticonsArray: [HMEmoticon] = {
        return self.loadEmoticonsArray(folderName: "lxh", fileName: "info.plist")
    }()
    
    //读取表情数据
    private func loadEmoticonsArray(folderName: String, fileName: String) -> [HMEmoticon] {
        let subPath = folderName + "/" + fileName
        //通过self.emoticonsBundle.path(forResource: <#T##String?#>, ofType: <#T##String?#>) 可以透过两层文件夹,直接到resources文件夹下查路径
        let path = self.emoticonsBundle.path(forResource: subPath, ofType: nil)!
        //获取资源数据
        let dicArray = NSArray(contentsOfFile: path) as! [[String: Any]]
        //使用yymodel把字典转成模型
        let modelArray = NSArray.yy_modelArray(with: HMEmoticon.self, json: dicArray) as! [HMEmoticon]
        //遍历数组模型,判断是图片类型,需要拼接路径
        for model in modelArray {
            if model.type == "0" {
                //表示图片,拼接完整路径
                let imagePath = self.emoticonsBundle.path(forResource: folderName, ofType: nil)!
                model.path = imagePath + "/" + model.png!
                //设置图片对应的文件夹名
                model.folderName = folderName
            }
        }
        return modelArray
    }
    
    //通过表情数组拆分成二维数组
    private func setctionEmoticon(emoticonArray: [HMEmoticon] ) -> [[HMEmoticon]]{
        //根据数组个数计算页数
        let pageCount = (emoticonArray.count - 1) / numberOfPage + 1
        //保存截取的表
        var tempArray = [[HMEmoticon]]()
        //遍历页数,截取相应的数据
        for i in 0..<pageCount {
            //开始截取的索引
            let loc = i * numberOfPage
            //截取的长度
            var len = numberOfPage
            //表示越界,获取剩余截取的个数
            if loc + len > emoticonArray.count {
                len = emoticonArray.count - loc
            }
            let subArray = (emoticonArray as NSArray).subarray(with: NSMakeRange(loc, len)) as! [HMEmoticon]
            tempArray.append(subArray)
        }
        return tempArray
    }
    
    //根据点击的表情模型保存到最近表情数组中
    func saveRecentEmoticonArray(emoticon: HMEmoticon) {
        //1.添加表情模型之前,判断最近表情数组里面是否已经存在对应的表情
        //如果存在,删除指定表情
        for (i,etn) in recentEmoticonArray.enumerated() {
            if emoticon.type == "0" {
                //表示图片,判断表情描述是否相同
                if etn.chs == emoticon.chs {
                    //相同
                    recentEmoticonArray.remove(at: i)
                    break
                }
            } else {
                //表示emoji,判断code
                if etn.code == emoticon.code {
                    //相同
                    recentEmoticonArray.remove(at: i)
                    break
                }
            }
        }
        //2.点击表情添加到最近表情数组的第一个元素
        recentEmoticonArray.insert(emoticon, at: 0)
        //3.如果超过20个,删除最后一个
        while recentEmoticonArray.count > 20 {
            recentEmoticonArray.removeLast()
        }
        //4.更新数据源
        allEmoticonsArray[0][0] = recentEmoticonArray
        //5.最近表情进行归档
        NSKeyedArchiver.archiveRootObject(recentEmoticonArray, toFile: RecentDataPath)
    }
    
    //从沙盒中获取最近表情数据
    private func loadRecentEmoticonArray() -> [HMEmoticon]?{
        return NSKeyedUnarchiver.unarchiveObject(withFile: RecentDataPath) as? [HMEmoticon]
    }
    
    //根据表情描述查找默认表情和浪小花表情数组
    func selectedEmoticon(chs: String) -> HMEmoticon? {
        //默认表情里面找
        for emoticon in defaultEmoticonsArray {
            if emoticon.chs == chs {
                return emoticon
            }
        }
        //lxh
        for emoticon in lxhEmoticonsArray {
            if emoticon.chs == chs {
                return emoticon
            }
        }
        return nil
    }
}
